package com.sharyuke.viam.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.sharyuke.viam.databinding.ActivityMainBinding
import com.sharyuke.viam.ui.base.BaseViewActivity
import com.sharyuke.viam.utils.onSearch


class MainActivity : BaseViewActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {
    @SuppressLint("SetJavaScriptEnabled")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        hasView {
            mainEt.onSearch {
                if (it.isEmpty()) return@onSearch
                val url = if (it.startsWith("http")) it else "http://%s".format(it)
                setText(url)
                mainWebview.loadUrl(url)
            }
            val webSettings: WebSettings = mainWebview.settings
            webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            webSettings.javaScriptEnabled = true
            webSettings.domStorageEnabled = true
            mainWebview.webViewClient = object : WebViewClient() {
                @SuppressLint("QueryPermissionsNeeded")
                override fun shouldOverrideUrlLoading(view: WebView?, url: String): Boolean {
                    view?.loadUrl(url)
                    mainEt.setText(url)
                    return true
                }
            }
            onBack { if (mainWebview.canGoBack()) mainWebview.goBack() else finish() }
        }
    }
}